import React, { useState, useEffect } from "react";
import { Box, Progress, Heading, Text } from "@chakra-ui/core";
import { useHistory } from "react-router-dom";
import { initialized } from "../lib/graphql-api";

const getCurrentProgress = async () =>
  ((await initialized()).enterprises || []).length > 0 ? 100 : 0;

const Initializer = () => {
  const [progressValue, setProgressValue] = useState(0);
  const history = useHistory();
  useEffect(() => {
    let itv = null;
    if (progressValue === 0) {
      getCurrentProgress().then((value) => {
        setProgressValue(value);
        if (value < 100) {
          itv = setInterval(async () => {
            setProgressValue(await getCurrentProgress());
          }, 3000);
        } else {
          setTimeout(() => {
            history.replace("/");
          }, 500); // 显示 Loading 过程
        }
      });
    }
    return function cleanUpTimer() {
      itv && clearInterval(itv);
    };
  });
  return (
    <Box display="flex" alignItems="center" justifyContent="center" h="100%">
      <Box
        w="xl"
        borderWidth="1px"
        rounded="lg"
        overflow="hidden"
        textAlign="center"
        p="4"
      >
        <Heading as="h2" fontSize="xl" fontWeight="400">
          初始化企业中...
        </Heading>
        <Text color="gray.500" mt="2" fontSize="sm">
          初始化完成后页面将自动刷新。
        </Text>
        <Progress
          mt="3"
          rounded="sm"
          hasStripe
          isAnimated
          value={progressValue}
        />
      </Box>
    </Box>
  );
};

export default Initializer;
